
package br.com.aeternu.controleatendimento.manutencao.agenda.ui;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.apache.log4j.Logger;
import br.com.aeternu.controleatendimento.common.ui.EasyJFrame;
import br.com.aeternu.controleatendimento.common.ui.TableCellListener;
import br.com.aeternu.controleatendimento.util.DateUtil;
import br.com.aeternu.controleatendimento.util.FormatUtil;

public class UIAgenda extends EasyJFrame
{

   private static final long serialVersionUID = 1L;
   private static Logger logger = Logger.getLogger(UIAgenda.class);
   private JButton btnNovaAgendadata;
   private JPanel contentPane;
   private IfcUIAgenda listener;
   private JScrollPane scrollPane;
   private JTable table;

   Action action = new AbstractAction()
   {

      private static final long serialVersionUID = 1L;

      public void actionPerformed(ActionEvent e)
      {
         TableCellListener tcl = (TableCellListener) e.getSource();
         logger.info("Row   : " + tcl.getRow());
         logger.info("Column: " + tcl.getColumn());
         logger.info("Old   : " + tcl.getOldValue());
         logger.info("New   : " + tcl.getNewValue());

         if (tcl.getOldValue() != tcl.getNewValue())
            atualizaPlanilha(tcl.getRow(), tcl.getColumn(), tcl.getNewValue());
      }
   };

   public UIAgenda(IfcUIAgenda listener)
   {
      super("Agendas");

      this.listener = listener;

      new TableCellListener(getTable(), action);

      initComponents();
   }

   public JButton getBtnNovaAgendadata()
   {
      if (btnNovaAgendadata == null)
      {
         btnNovaAgendadata = new JButton("Criar Agenda");
         btnNovaAgendadata.setMnemonic('C');
         btnNovaAgendadata.addActionListener(new ActionListener()
         {

            public void actionPerformed(ActionEvent e)
            {
               btnNovaAgendadataActionPerformed();
            }
         });
      }
      return btnNovaAgendadata;
   }

   public JScrollPane getScrollPane()
   {
      if (scrollPane == null)
      {
         scrollPane = new JScrollPane();
         scrollPane.setViewportView(getTable());
      }
      return scrollPane;
   }

   public JTable getTable()
   {
      if (table == null)
      {
         table = new JTable();
         table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         table.setDefaultRenderer(String.class, new BackgroundTableCellRenderer());
         table.setModel(getTableModel());
         table.getColumnModel().getColumn(0).setResizable(false);
         table.getColumnModel().getColumn(0).setPreferredWidth(100);
         table.getColumnModel().getColumn(0).setMinWidth(100);
         table.getColumnModel().getColumn(0).setMaxWidth(100);
         table.getColumnModel().getColumn(1).setResizable(false);
         table.getColumnModel().getColumn(1).setPreferredWidth(100);
         table.getColumnModel().getColumn(1).setMinWidth(100);
         table.getColumnModel().getColumn(1).setMaxWidth(100);
         table.getColumnModel().getColumn(2).setResizable(false);
         table.getColumnModel().getColumn(2).setPreferredWidth(100);
         table.getColumnModel().getColumn(2).setMinWidth(100);
         table.getColumnModel().getColumn(2).setMaxWidth(100);
      }
      return table;
   }

   @Override
   public void sair()
   {
      dispose();
   }

   private void atualizaPlanilha(int row, int column, Object newValue)
   {
      listener.atualizaPlanilha(this, row, column, newValue);
   }

   private void btnNovaAgendadataActionPerformed()
   {
      listener.incluirAgenda(this);
   }

   private TableModel getTableModel()
   {
      return new DefaultTableModel(
         new Object[][]{
            {null, null, null},
         },
         new String[]{
            "Data", "Matutino", "Vespertino"
         })
      {

         private static final long serialVersionUID = 1L;
         boolean[] columnEditables = new boolean[]{
            false, true, true
         };

         Class<?>[] columnTypes = new Class[]{
            String.class, Integer.class, Integer.class
         };

         public Class<?> getColumnClass(int columnIndex)
         {
            return columnTypes[columnIndex];
         }

         public boolean isCellEditable(int row, int column)
         {
            if (column == 0 && getValueAt(row, 0) == null)
               return true;

            if ((column == 1 || column == 2) && DateUtil.isUtil((String) getValueAt(row, 0)))
               return true;

            return columnEditables[column];
         }
      };
   }

   private void initComponents()
   {
      setResizable(false);
      setBounds(100, 100, 340, 500);
      contentPane = new JPanel();
      contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
      setContentPane(contentPane);
      GroupLayout gl_contentPane = new GroupLayout(contentPane);
      gl_contentPane.setHorizontalGroup(
               gl_contentPane.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_contentPane.createSequentialGroup()
                                 .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                                          .addComponent(getBtnNovaAgendadata())
                                          .addComponent(getScrollPane(), GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE))
                                 .addGap(0))
               );
      gl_contentPane.setVerticalGroup(
               gl_contentPane.createParallelGroup(Alignment.TRAILING)
                        .addGroup(gl_contentPane.createSequentialGroup()
                                 .addComponent(getScrollPane(), GroupLayout.DEFAULT_SIZE, 416, Short.MAX_VALUE)
                                 .addGap(24)
                                 .addComponent(getBtnNovaAgendadata()))
               );
      contentPane.setLayout(gl_contentPane);
      setVisible(true);
   }

   class BackgroundTableCellRenderer extends DefaultTableCellRenderer
   {

      private static final long serialVersionUID = 1L;

      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
      {
         DateFormat df = new SimpleDateFormat(FormatUtil.DATE_FORMAT);
         Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
         String dataAsString = (String) table.getModel().getValueAt(row, 0);

         if (!dataAsString.equals(""))
         {
            try
            {
               Date data = df.parse(dataAsString);
               Calendar cal = Calendar.getInstance();
               cal.setTime(data);

               if (!DateUtil.isUtil(cal))
               {
                  c.setBackground(new Color(224, 167, 148, 100));
                  c.setForeground(Color.BLACK);
               }
               else
               {
                  c.setBackground(Color.WHITE);
                  c.setForeground(Color.BLACK);
               }
            }
            catch (ParseException e)
            {
               e.printStackTrace();
            }
         }

         return c;
      }
   }
}
